package com.dong.dynamicProgramming;

/**
 * @author dcz
 * @classname CanPartition
 * @description 分割等和子集
 * @date 2022/5/2 9:28
 */
public class CanPartition {
    public static void main(String[] args) {
        int[] nums = {1,5,11,5};
        boolean b = canPartition(nums);
        System.out.println(b);
    }

    public static  boolean canPartition(int[] nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }

        if (sum % 2 == 1){
            return false;
        }

        int target = sum / 2;

        //dp[i][j]代表可装物品为0-i，背包容量为j的情况下，背包内容量的最大价值
        //dp[i][j]前i个元素，背包容量为j的情况下的和
        int[][] dp = new int[nums.length][target + 1];

        //初始化,dp[0][j]的最大价值nums[0](if j > weight[i])
        //dp[i][0]均为0，不用初始化
        for (int j = nums[0]; j <= target; j++) {
            dp[0][j] = nums[0];
        }
        /*
                  0 1 2 3 4 5 6 7 8 9 10 11
        (1)元素0  0 1 1 1 1 1 1 1 1 1  1 1
        (5)元素1  0 1 1 1 1 5 6 6 6 6  6 6
        (11元素2  0 1 1 1 1 5 6 6 6 6  6 11
        (5)元素3  0 1 1 1 1 5 6 6 6 6 10 11
         */

        //遍历物品，再遍历背包
        for (int i = 1; i < nums.length; i++) {
            for (int j = 1; j <= target; j++) {
                //背包容量可以容纳nums[i]
                if (j >= nums[i]) {
                    //相当于背包里放入数值，那么物品i的重量是nums[i]，其价值也是nums[i]
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - nums[i]] + nums[i]);
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        //打印dp数组
        for (int i = 0; i < nums.length; i++){
            for (int j = 0; j <= target; j++){
                System.out.print(dp[i][j] + " ");
            }
            System.out.print("\n");
        }

        return dp[nums.length - 1][target] == target;

    }

    public boolean canPartition2(int[] nums) {
        if(nums == null || nums.length == 0){
            return false;
        }
        int n = nums.length;
        int sum = 0;
        for(int num : nums){
            sum += num;
        }
        //总和为奇数，不能平分
        if(sum % 2 != 0) {
            return false;
        }
        int target = sum / 2;
        int[] dp = new int[target + 1];
        for(int i = 0; i < n; i++){
            for(int j = target; j >= nums[i]; j--){
                //物品 i 的重量是 nums[i]，其价值也是 nums[i]
                dp[j] = Math.max(dp[j], dp[j-nums[i]] + nums[i]);
            }
        }
        return dp[target] == target;
    }


}
